<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/* Start of file GetResource.php */
/*
 * This part help to get templates from
 * templatemonster.com,
 */

class GetResource extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->helper('file');
    }
    public function Home(){
        
        $data['survey_title']="Lấy thông tin địa chỉ nguồn";
        $this->load->view('templates/default/header',$data);
        $this->load->view('getresource_home');
        $this->load->view('templates/default/footer');
        
    }
    public function Test(){
        
        $data['survey_title']="Đang lấy thông tin... ";
        $data['result']='';
        
        if(isset($_POST['url'])){
            $url=$_POST['url'];/* Get URL information of domain*/
            $data['result']=$this->get_resource($url,'./assets/resources/template/test');//test cUrl
        }else{
            redirect('/GetResource/Home','location',301);
        }
        
        /* Show View */
        $this->load->view('templates/default/header',$data);
        $this->load->view('getresource_getting',$data);
        $this->load->view('templates/default/footer');
        /* -- End of view part -- */
        
    }

    
    /* Supporting functions  */
    public function get_resource($url,$path){
        /* Initital */
        $output = file_get_contents($url); 
        $result='';
        
        $urlparts= explode('/', $url);
        $result.='URL: '.implode('/', $urlparts).'<br>'. json_encode(parse_url($url));
        $url_pars=parse_url($url);
        $result.=json_encode(pathinfo($url_pars["path"])).'<br>';
        
        /* Choose suitable extension */
        $extension=strtolower(pathinfo($url, PATHINFO_EXTENSION));
        if($extension==NULL || in_array($extension,array('php','asp','aspx','htm')))
            $extension='html';
        $extension='.'.$extension;
        
        $valid_name=$this->get_valid_name_for_save($url, $extension);
        $result.='Filename: '.$path.'/'.$valid_name.'<br>';
        
        /* Write file to Server HDD */
        //$result.=$this->write_file($path, $valid_name, $output);
        
        /* Parts for saving files */
        if($extension=='.html'){
            /* Get DOM model */
            $dom = new DOMDocument;
            libxml_use_internal_errors(true);
            $dom->loadHTML($output);
            libxml_clear_errors();
            //echo serialize($output);
            
            /* Get URLs inside of HTML source code */
            $result.='<br><strong>:: List of Img link </strong><br>';
            foreach ($dom->getElementsByTagName('img') as $node)
            {
                $new_node=$node->getAttribute("src");

                if($this->check_href($new_node)==true){
                    $result.=$this->get_resource($this->get_URL_from_physical_url($url, $new_node), 
                            $path.'/'.$this->get_current_path_for_save($url, $new_node));
                }
            }

            $result.='<strong>:: List of CSS link </strong><br>';
            /* Get list of Head Link/CSS links */
            
            foreach ($dom->getElementsByTagName('link') as $node)
            {
                $new_node=$node->getAttribute("href");
                if($this->check_href($new_node)==true){
                    //$result.=$this->get_URL_from_physical_url($url, $new_node).'<br>';
                    //$result.=$this->get_current_path_for_save($url, $new_node).'<br>';
                    $result.=$this->get_resource($this->get_URL_from_physical_url($url, $new_node), 
                            $path.'/'.$this->get_current_path_for_save($url, $new_node));
                }
            }

            $result.='<strong>:: List of javascript link</strong> <br>';
            /* Get List of js links */
            foreach ($dom->getElementsByTagName('script') as $node)
            {
                $new_node=$node->getAttribute("src");
                if($this->check_href($new_node)==true){
                    $result.=$this->get_resource($this->get_URL_from_physical_url($url, $new_node), 
                            $path.'/'.$this->get_current_path_for_save($url, $new_node));
                }
            }
        } else if ($extension=='.css'){
           // $result.=$output;
            $output = str_replace("  ", " ", $output);
            $output =  str_replace("url (", "url(", $output);
            $word_url__pos = strpos($output,"url(",0);
            //echo $word_url__pos.'<br>';
            while($word_url__pos!==FALSE){
                $parenthesis__pos=strpos($output,")",$word_url__pos);
                if($parenthesis__pos!==FALSE){
                    $external_link =  substr($output, $word_url__pos, $parenthesis__pos-$word_url__pos+1);
                    $result.=$external_link.'<br>';
                    
                    $external_link = str_replace(array("url(",")","'",'"'),"", $external_link);
                    
                    echo $this->get_current_path_for_save($url, $external_link),'<br>';
                    echo $this->get_URL_from_physical_url($url, $external_link),'<br><br>';
                    $word_url__pos = strpos($output,"url(",$parenthesis__pos);
                }else break;
            }
        }
        
        return $result;
        
    }
    
    function write_file($path,$valid_name,$content){
        
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        if ( ! write_file($path.'/'.$valid_name , $content,'w+'))
        {
            return 'Logs: Unable to write the file '.$path.'/'.$valid_name.'<br>';
        }
        else
        {
            return  'Logs: Copied to '.$path.'/'.$valid_name.'<br>';
        }
    }
    
    function get_current_path_for_save($url,$physical_url){
        if(strpos($physical_url,"//")===0||strpos($physical_url,"http://")===0||strpos($physical_url,"https://")===0){
                return NULL;
        }
        $physical_parts = parse_url($physical_url);
        $physical_path = pathinfo($physical_parts["path"]);
        if(strpos($physical_path["dirname"],"./")===0){
            $physical_path["dirname"]=  substr($physical_path["dirname"], 2);
        }else if(strpos($physical_path["dirname"],"/")===0){
            $physical_path["dirname"]=  'unknown_parent/'.$physical_path["dirname"];
        }
        return $physical_path["dirname"];
        
    }
    
    function get_valid_name_for_save($url,$extension){
        $validname='unknown.dat';
        $urlparts= explode('/', $url);
        
        /* Checking and get valid part for naming */
        for($i=count($urlparts)-1;$i>=0;$i--){
            if(strlen($urlparts[$i])>0){//check if this part has content
                
                if(strpos($urlparts[$i],'?')!==NULL){
                    $nameparts= explode('?', $urlparts[$i]);
                    if(strlen($nameparts[0])>0){
                        $validname=$nameparts[0];
                    } else {
                        break;
                    }
                } else {
                    $validname=$urlparts[$i];
                }
                
                if(strpos($validname,'#')!==NULL){
                    $validname=  str_replace("#", "-", $validname);
                }
                
                if(strpos($validname,'?')===NULL){
                    $validname.=$extension;
                }else{
                    $val_temp=  explode('.',$validname);
                    if(strlen($val_temp[0])>0){
                        if(count($val_temp)>1)
                            unset($val_temp[count($val_temp)-1]);
                        $validname=  implode(".", $val_temp).$extension;
                    }else{
                        $validname='unknown'.$extension;
                    }
                }
                break;
            }
        }
        return $validname;
    }
    
    function get_URL_from_physical_url($url,$physical_url){
        
        if(strpos($physical_url,"//")===0||strpos($physical_url,"http://")===0||strpos($physical_url,"https://")===0){
            return $physical_url;
        }
        
        $result="";
        $url_parts=parse_url($url);
        $physical_parts=parse_url($physical_url);
        
        if(!isset($physical_parts["host"])){
            $physical_parts["host"]=$url_parts["host"];
            $physical_parts["scheme"]=$url_parts["scheme"];
        }
        
        if(strpos($physical_parts["path"],"/")===0){
            $result=$physical_parts['scheme'].'://'.$physical_parts["host"].$physical_parts["path"];
        } else if(strpos($physical_parts["path"],"./")===0){
            $infopath = pathinfo($url_parts["path"]);
            $result=$physical_parts['scheme'].'://'.$physical_parts["host"].$infopath["dirname"].substr($physical_parts["path"],1);
        }
        else {
            $infopath = pathinfo($url_parts["path"]);
            $result=$physical_parts['scheme'].'://'.$physical_parts["host"].$infopath["dirname"].'/'.$physical_parts["path"];
        }
        
        return $result;
    }
    
    function check_href($url){
        $pos=strpos($url, "javascript:");
        if($pos!=NULL) return false;
        if(strlen($url)<=1) return false;
        return true;
    }
    
    function check_img($url){
        $pos=strpos($url, "javascript:");
        if($pos!=NULL) return false;
        if(strlen($url)<=1) return false;
        return true;

    }
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */